package com.atguigu.gulimall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberVo;
import com.atguigu.gulimall.seckill.feign.CouponFeignService;
import com.atguigu.gulimall.seckill.feign.ProductFeignService;
import com.atguigu.gulimall.seckill.intercepter.LoginUserInterceptor;
import com.atguigu.gulimall.seckill.service.SeckillService;
import com.atguigu.gulimall.seckill.to.SecKillSkuRedisTo;
import com.atguigu.gulimall.seckill.vo.SeckillSessionsWithSkus;
import com.atguigu.gulimall.seckill.vo.SeckillSkuVo;
import com.atguigu.gulimall.seckill.vo.SkuInfoVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @ClassName SeckillServiceImpl
 * @Description 商品上架业务
 * @Detail detail
 * @Author MyPC
 * @Date 2020/7/27
 * @Version 1.0
 */
@Service
public class SeckillServiceImpl implements SeckillService {
    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    RabbitTemplate rabbitTemplate;

    //session前缀
    private final String SESSIONS_CACHE_PREFIX="seckill:sessions:";
    //秒杀商品的前缀
    private final String SKUKILL_CACHE_PREFIX="seckill:skus";

    private final String SKU_STOCK_SEMAPHORE="seckill:stock:"; //+商品随机码

    /**
     * 商品上架
     */
    @Override
    public void UploadSeckillSkuLatest3Days() {
        R r = couponFeignService.UploadSeckillSkuLatest3Days();
        if(r.getCode() == 0){
            List<SeckillSessionsWithSkus> sessionsWithSkuses = r.getData(new TypeReference<List<SeckillSessionsWithSkus>>() {
            });
            if(sessionsWithSkuses != null && sessionsWithSkuses.size()>0){
                //缓存到redis
                //1、缓存活动信息
                saveSessionInfos(sessionsWithSkuses);
                //2、缓存秒杀商品详情信息
                saveSessionSkuInfos(sessionsWithSkuses);
            }
        }
    }

    /**
     * 获取当前秒杀场次的所有秒杀商品
     * @return
     */
    @Override
    public List<SecKillSkuRedisTo> getCurrentSeckillSkus() {
        //1、获取当前时间的秒杀场次
        long current = new Date().getTime();
        Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
        for (String key : keys) {
            //key的形式： seckill:sessions:1596384000000_1596387600000
            String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
            String[] split = replace.split("_");
            Long start=Long.parseLong(split[0]);
            Long end=Long.parseLong(split[1]);
            if(current>=start && current<=end){
                //2、获取当前秒杀场次所有的秒杀商品信息
                List<String> range = redisTemplate.opsForList().range(key, -100L, 100L);
                BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                List<String> list = hashOps.multiGet(range);
                if(list !=null && list.size()>0){
                    List<SecKillSkuRedisTo> collect = list.stream().map(item -> {
                        SecKillSkuRedisTo secKillSkuRedisTo = JSON.parseObject(item, SecKillSkuRedisTo.class);
                        return secKillSkuRedisTo;
                    }).collect(Collectors.toList());
                    return collect;
                }
                break;
            }
        }
        return null;
    }

    /**
     * 获取商品的秒杀活动信息
     * @param skuId
     * @return
     */
    @Override
    public SecKillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();
        if(keys != null && keys.size()>0){
            //正则表达式
            String regx="\\d_"+skuId;
            for (String key : keys) {
                if(Pattern.matches(regx,key)){
                    String obj = hashOps.get(key);
                    SecKillSkuRedisTo secKillSkuRedisTo = JSON.parseObject(obj, SecKillSkuRedisTo.class);
                    long current = new Date().getTime();
                    if(current >= secKillSkuRedisTo.getStartTime() && current <= secKillSkuRedisTo.getEndTime()){

                    }else {
                        //如果当前商品并不在秒杀时间内，则随机码置空
                        secKillSkuRedisTo.setRandomCode(null);
                    }
                    return secKillSkuRedisTo;
                }
            }
        }
        return null;
    }

    /**
     * 秒杀商品
     * @param killId
     * @param key
     * @param num
     * @return
     */
    @Override
    public String kill(String killId, String key, Integer num) {
        MemberVo memberVo = LoginUserInterceptor.threadLocal.get();
        //1、获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String get = hashOps.get(killId);
        if(!StringUtils.isEmpty(get)){
            //有该场次信息
            SecKillSkuRedisTo skuRedisTo = JSON.parseObject(get, SecKillSkuRedisTo.class);
            //2、验证时间的合法性
            Long startTime = skuRedisTo.getStartTime();
            Long endTime = skuRedisTo.getEndTime();
            long current = new Date().getTime();
            //自动过期时间
            long ttl=endTime-current;
            if(current >= startTime && current <= endTime){
                //3、校验随机码和场次id
                String nowKillId=skuRedisTo.getPromotionSessionId()+"_"+skuRedisTo.getSkuId();
                String randomCode=skuRedisTo.getRandomCode();
                if(killId.equals(nowKillId) && key.equals(randomCode)){
                    //4、校验购买数量是否合理
                    if(num<=skuRedisTo.getSeckillLimit().intValue()){
                        //5、校验该用户是否已经买过,幂等性，只要该用户买过，就去站位 userId_sessionId_skuId
                        String redisKey=memberVo.getId()+"_"+nowKillId;
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MICROSECONDS);
                        if(aBoolean !=null && aBoolean){
                            //占位成功，说明从来没有买过
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                            boolean b = semaphore.tryAcquire(num);
                            if(b){
                                //6、秒杀成功，下单，向MQ发送消息
                                String orderSn = IdWorker.getTimeId();
                                SeckillOrderTo seckillOrder = new SeckillOrderTo();
                                seckillOrder.setOrderSn(orderSn);
                                seckillOrder.setMemberId(memberVo.getId());
                                seckillOrder.setNum(num);
                                seckillOrder.setPromotionSessionId(skuRedisTo.getPromotionSessionId());
                                seckillOrder.setSeckillPrice(skuRedisTo.getSeckillPrice());
                                seckillOrder.setSkuId(skuRedisTo.getSkuId());
                                rabbitTemplate.convertAndSend("order-event-exchange","order.seckill.order",seckillOrder);
                                //7、返回订单号
                                return orderSn;
                            }
                            return null;
                        }else {
                            return null;
                        }
                    }else {
                        return null;
                    }
                }else {
                    return null;
                }
            }else {
                return null;
            }
        }
        return null;
    }

    /**
     * 缓存活动信息
     * @param sessions
     */
    private void saveSessionInfos(List<SeckillSessionsWithSkus> sessions){
        sessions.stream().forEach(session -> {
            long start = session.getStartTime().getTime();
            long end = session.getEndTime().getTime();
            String key = SESSIONS_CACHE_PREFIX+start+"_"+end;
            Boolean aBoolean = redisTemplate.hasKey(key);
            if(!aBoolean){
                //如果秒杀活动已经保存在redis了，就无需再保存一份了
                //该活动中对应的秒杀商品的skuId
                List<String> skuIds = session.getRelationEntities().stream().map(item -> item.getPromotionSessionId().toString()+"_"+item.getSkuId().toString()).collect(Collectors.toList());
                redisTemplate.opsForList().leftPushAll(key,skuIds);
            }
        });
    }

    /**
     * 缓存秒杀商品详情信息
     * @param sessions
     */
    private void saveSessionSkuInfos(List<SeckillSessionsWithSkus> sessions){
        sessions.stream().forEach(session -> {
            //获取hash操作
            BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            session.getRelationEntities().stream().forEach(seckillSkuVo -> {
                if(!hashOps.hasKey(seckillSkuVo.getPromotionSessionId().toString()+"_"+seckillSkuVo.getSkuId().toString())){
                    SecKillSkuRedisTo redisTo=new SecKillSkuRedisTo();
                    R r = productFeignService.getSkuInfo(seckillSkuVo.getSkuId());
                    if(r.getCode() == 0){
                        //1、sku的基本数据
                        SkuInfoVo skuInfoData = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        redisTo.setSkuInfo(skuInfoData);
                    }
                    //2、sku的秒杀信息
                    BeanUtils.copyProperties(seckillSkuVo,redisTo);
                    //3、设置秒杀商品的开始和结束时间
                    redisTo.setStartTime(session.getStartTime().getTime());
                    redisTo.setEndTime(session.getEndTime().getTime());
                    //4、sku的秒杀随机码,用户秒杀商品时没有携带随机码是秒杀不了商品的
                    String randomCode = UUID.randomUUID().toString().replace("-", "");
                    redisTo.setRandomCode(randomCode);
                    String string = JSON.toJSONString(redisTo);
                    hashOps.put(seckillSkuVo.getPromotionSessionId().toString()+"_"+seckillSkuVo.getSkuId().toString(),string);
                    //5、设置分布式信号量,使用库存作为分布式信号量，可以限流
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                    semaphore.trySetPermits(seckillSkuVo.getSeckillCount().intValue());
                }
            });
        });
    }
}
